package com.omega.framework.common.validate.aop;

import com.omega.framework.common.validate.template.CheckFieldTemplate;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

/**
 * 校验框架拦截
 *
 * @author Lv.
 * @date 2023/8/29 16:45
 */
@Aspect
@Configuration
public class ServiceValidateAspect {
    private static final Logger log = LoggerFactory.getLogger(ServiceValidateAspect.class);

    private final CheckFieldTemplate checkFieldTemplate;

    private final ThreadLocal<Long> startTime = new ThreadLocal<>();

    public ServiceValidateAspect(CheckFieldTemplate checkFieldTemplate) {
        this.checkFieldTemplate = checkFieldTemplate;
    }

    @Pointcut("@annotation(com.omega.framework.common.validate.annotation.ValidateRequest)")
    public void validateRequest() {
    }

    @Around("validateRequest()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {

        try {
            Object[] var3 = joinPoint.getArgs();
            for (Object param : var3) {
                this.checkFieldTemplate.checkField(param);
            }
            log.info("执行耗时 :{}ms", System.currentTimeMillis() - startTime.get());
        } finally {
            startTime.remove();
        }
        return joinPoint.proceed();
    }
}
